let app = getApp()
Page({
  data: {
    hasNum: null,
    renshu: 0,
    renshulist: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
  },
  onShow() {
    console.log('全局存的桌号：', app.globalData.zhuohao)
    let list = wx.getStorageSync('cart') || []
    console.log('本地缓存的list', list)
    this.setData({
      list,
      hasNum: app.globalData.zhuohao
    })
    this.getTotal()
  },
  // 计算总价格和总数量
  getTotal() {
    let cartList = this.data.list
    let totalMoney = 0
    let totalNum = 0

    cartList.forEach(item => {
      totalNum += item.quantity;
      totalMoney += item.quantity * item.price
    })
    this.setData({
      totalMoney,
      totalNum
    })
  },
  // 扫码识别桌号
  saoma() {
    console.log('点击了扫码识别桌号')
    // let that = this
    // wx.scanCode({
    //   success(res) {
    //     console.log(res.result)
    //     that.setData({
    //       hasNum: res.result
    //     })
    //   }
    // })

    wx.scanCode({
      success: res => {
        console.log(res.result)
        app.globalData.zhuohao = res.result
        this.setData({
          hasNum: res.result
        })
      }
    })
  },
  // 选择就餐人数
  xuanzhong(e) {

    this.setData({
      renshu: e.currentTarget.dataset.item
    })
  },
  // 获取用户输入的备注信息
  getBeizhu(e) {
    this.setData({
      beizhu: e.detail.value
    })
  },
  // 提交订单
  submit() {
    if (!this.data.hasNum) {
      wx.showToast({
        icon: 'error',
        title: '请识别桌号',
      })
    } else if (!this.data.renshu) {
      wx.showToast({
        icon: 'error',
        title: '选择就餐人数',
      })
    } else {
      console.log('执行了提交订单')
      let user = wx.getStorageSync('user')
      console.log('用户信息', user)
      // 校验用户是否登陆
      if (!user) {
        wx.showToast({
          icon: 'error',
          title: '去个人中心登陆',
        })
        setTimeout(() => {
          wx.switchTab({
            url: '/pages/me/me',
          })
        }, 1000);
        return

      }
      // 提交订单
      wx.cloud.database().collection('order')
        .add({
          data: {
            name: user.nickName, //用户的昵称
            status: 0, //订单状态 -1订单取消,0新下单待上餐,1待用户评价,2订单已完成
            address: this.data.hasNum, //桌号
            beizhu: this.data.beizhu, //用户的备注
            renshu: this.data.renshu, //就餐人数
            orderList: this.data.list, //用户点了那些菜
            totalPrice: this.data.totalMoney, //总价
            _createTime: app.getCurrentTime()
          }
        }).then(res => {
          console.log('提交订单成功', res)
          // 清空购物车
          wx.setStorageSync('cart', null)

          wx.switchTab({
            url: '/pages/me/me',
          })
        }).catch(res => {
          console.log('提交订单失败', res)
        })
    }
  }
})